﻿using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using System;
using System.Web;
using System.Net;
using ElectronicShoppingMall.Web.Front.DTOS;
using ElectronicShoppingMall.Service.Services.Enterprise;
using ElectronicShoppingMall.Service.Services.Client;

namespace ElectronicShoppingMall.Web.Front
{
    public class CustomOAuthProvider : OAuthAuthorizationServerProvider
    {
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var account = context.UserName;
            var password = context.Password;
            int userId;
            string nickname;
            if (!CheckCredential(account, password, out userId, out nickname))
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                context.Rejected();
                return Task.FromResult<object>(null);
            }
            var ticket = new Microsoft.Owin.Security.AuthenticationTicket(SetClaimsIdentity(context, userId, account, nickname), new AuthenticationProperties());
            context.Validated(ticket);
            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context, int userid, string account, string nickname)
        {
            var identity = new ClaimsIdentity("JWT");
            identity.AddClaim(new Claim("userId", userid + ""));
            identity.AddClaim(new Claim("account", account));
            identity.AddClaim(new Claim("nickname", nickname));
            return identity;
        }

        private static bool CheckCredential(string account, string password, out int userId, out string nickname)
        {
            ClientUserService _service = new ClientUserService();
            var success = false;            // 用户名和密码验证
            try
            {
                var user = _service.Login(account, password);
                UserDTO currentUser = new UserDTO()
                {
                    Name = user.Name,
                    UserId = user.UserId,

                };
                userId = currentUser.UserId;
                nickname = currentUser.Name;
                success = true;
            }
            catch 
            {
                userId = 0;
                nickname = "";
                success = false;
            }
            return success;
        }
    }
}